#include <iostream>


// Exercise 6.10:
std::size_t
strlen(const char* s)
{
  const char* p = s;

  while (*p != '\0') ++p;

  return (p - s);
}


char*
strcpy(const char* s)
{
  char* t = new char();
  char* r = t;

  while (*s != '\0') *t++ = *s++;
  *t = '\0';

  return r;
}


std::size_t
strcmp1(const char* s, const char* t)
{
  std::size_t i = 1;
  
  while ((*s != '\0') && (*s++ == *t++)) ++i;

  return (*s == '\0' && *t == '\0') ? 0: i; 
}

// Exercise 6.13:
char* strcat(const char* s, const char* t)
{
  char* cat = new char();
  char* r = cat;
  
  while (*s != '\0') *cat++ = *s++;
  while (*t != '\0') *cat++ = *t++;

  *cat = '\0';

  return r;
}

// Exercise 6.14:
char*
strrev(const char* s)
{
  char* t = new char();
  char* r = t;
  const char* s1 = s;

  while (*s1 != '\0') ++s1;
  while (s1 != s) *t++ = *(--s1);
  *t = '\0';

  return r;
}

// Exercise 6.17
void
itoa(int i, char* b)
{
  char* s = b;
  char* t = new char();
  char* r = t;
  
  if (i < 0)
    {
      *s++ = '-';
      i = -i;
    }

  std::cerr << "Negative check passed" << std::endl;
  
  int j;
  while (i > 0)
    {
      j = i % 10;
      i /= 10;

      *t++ = '0' + j;
    }

  std::cerr << "Collecting passed" << std::endl;

  if (t == r) // i == 0
    {
      std::cerr << "Is zero" << std::endl;
      *s++ = '0';
      *s = '\0';
    }
  else
    {
      std::cerr << "Backwards collecting starts" << std::endl;
      while (t != r) *s++ = *(--t);
      std::cerr << "Backwards collecting ended" << std::endl;
      *s = '\0';
    }
}

int 
main()
{
  std::cout << strlen("string len") << std::endl;
  std::cout << strcpy("string copy ") << std::endl;
  std::cout << "Same strings: " << strcmp1("same string", "same string") << std::endl;
  std::cout << "Different strings: " << strcmp1("same string", "same different string") << std::endl;
  std::cout << "Different strings: " << strcmp1("same different string", "same string") << std::endl;
  std::cout << "cat(\"string 1\", \"string 2\") = " << strcat("string 1", "string 2") << std::endl;
  std::cout << "rev(\"what a string!\") = " << strrev("what a string!") << std::endl;

  char* b0 = new char();
  itoa(0, b0);
  
  char* b1230456 = new char();
  itoa(1230456, b1230456);

  char* bm1230456 = new char();
  itoa(-1230456, bm1230456);

  std::cout << "itoa(0) = " << b0 << std::endl;
  std::cout << "itoa(1230456) = " << b1230456 << std::endl;
  std::cout << "itoa(-1230456) = " << bm1230456 << std::endl;
}
